package corsi.jpa.demo.prima.servizi;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import org.apache.log4j.Logger;

import corsi.jpa.demo.prima.domain.CD;



public class ServizioCrud {

	
	private static Logger logger = Logger.getLogger(ServizioCrud.class);
	private EntityManager entityManager;;
	
	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
		
	
public void inserisci (CD daInserire){
		
		//Session sessione =emf.getCurrentSession();
		//sessione.beginTransaction();
			
		logger.info("prima inserimento ID: "+daInserire.getPrimaryKey());
		EntityTransaction tx = entityManager.getTransaction();
		tx.begin();
		entityManager.persist(daInserire);
		tx.commit();
		entityManager.close();
		logger.info("inserito con ID: "+daInserire.getPrimaryKey());
	 
	
	}

	public void modifica (CD daModificare){
		
		logger.info("ID oggetto in memoria: "+daModificare.getPrimaryKey());
		EntityTransaction tx = entityManager.getTransaction();
		tx.begin();	
		entityManager.merge(daModificare);
		tx.commit();
		entityManager.close();
		logger.info("modifica oggetto con ID: "+daModificare.getPrimaryKey());
		
	}
	
	
	public void cancella (CD daCancellare){
		
		EntityTransaction tx = entityManager.getTransaction();
		tx.begin();
		entityManager.remove(daCancellare);
		tx.commit();
		entityManager.close();
		logger.info("ID oggetto cancellato: "+daCancellare.getPrimaryKey());
		
		
		
	}
	
	
	public CD cerca (Class classe, long id){
	
		CD trovato = new CD();
		try {
			EntityTransaction tx = entityManager.getTransaction();
			tx.begin();
			trovato= (CD)entityManager.find(classe, id);
			tx.commit();
			entityManager.close();
			
		}
		catch (Exception e) {
		
			e.printStackTrace();
		}	
		return trovato;
	
	}
	
	
	
}
